import useSWR from "swr";
import { fetcher } from "../utils";
import { useState } from "react";
import "./GradeReport.css";

export default function GradeReport() {
    const [selectedStudent, setSelectedStudent] = useState(null);
    const { data: students, error: studentsError } = useSWR("/api/student/list", fetcher);
    const { data: gradesData, error: gradesError } = useSWR(
        selectedStudent ? `/api/grade/list` : null,
        fetcher
    );

    // 确保grades是数组，并过滤出选中学生的成绩
    const grades = Array.isArray(gradesData) 
        ? gradesData.filter(grade => grade.stu_sn === Number(selectedStudent))
        : [];

    if (studentsError) {
        return <div>学生数据加载失败</div>;
    }

    if (gradesError) {
        return <div>成绩数据加载失败</div>;
    }

    if (!students) {
        return <div>学生数据加载中...</div>;
    }

    const handleStudentChange = (event) => {
        setSelectedStudent(event.target.value);
    };

    // 计算统计数据
    const calculateStats = (grades) => {
        if (!Array.isArray(grades) || grades.length === 0) {
            return {
                totalCourses: 0,
                averageGrade: 0,
                maxGrade: 0,
                minGrade: 0
            };
        }
        
        const totalCourses = grades.length;
        const averageGrade = grades.reduce((sum, item) => sum + (Number(item.grade) || 0), 0) / totalCourses;
        const maxGrade = Math.max(...grades.map(item => Number(item.grade) || 0));
        const minGrade = Math.min(...grades.map(item => Number(item.grade) || 0));
        
        return {
            totalCourses,
            averageGrade,
            maxGrade,
            minGrade
        };
    };

    const stats = calculateStats(grades);

    return (
        <div className="paper">
            <div className="paper-head">
                <h2>学生成绩报告</h2>
                <div className="student-selector">
                    <select 
                        value={selectedStudent || ''} 
                        onChange={handleStudentChange}
                        className="select-input"
                    >
                        <option value="">请选择学生</option>
                        {students && students.map(student => (
                            <option key={student.stu_sn} value={student.stu_sn}>
                                {student.stu_name}
                            </option>
                        ))}
                    </select>
                </div>
            </div>
            <div className="paper-body">
                {selectedStudent ? (
                    <>
                        <div className="report-stats-simple">
                            <span><strong>总课程数：</strong> <span className="stats-value">{stats.totalCourses}</span></span>
                            <span><strong>平均成绩：</strong> <span className="stats-value">{stats.averageGrade.toFixed(2)}</span></span>
                            <span><strong>最高成绩：</strong> <span className="stats-value">{stats.maxGrade}</span></span>
                            <span><strong>最低成绩：</strong> <span className="stats-value">{stats.minGrade}</span></span>
                        </div>
                        {grades.length > 0 ? (
                            <div className="grade-details">
                                <h3>成绩明细</h3>
                                <table className="table">
                                    <thead>
                                        <tr>
                                            <th>课程名称</th>
                                            <th>成绩</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        {grades.map((grade, index) => (
                                            <tr key={index}>
                                                <td>{grade.cou_name}</td>
                                                <td>{grade.grade}</td>
                                            </tr>
                                        ))}
                                    </tbody>
                                </table>
                            </div>
                        ) : (
                            <div className="no-selection">
                                该学生暂无成绩记录
                            </div>
                        )}
                    </>
                ) : (
                    <div className="no-selection">
                        请选择学生查看成绩报告
                    </div>
                )}
            </div>
        </div>
    );
}